"use client";
import { useState, useEffect, useCallback } from "react";
import { useRouter } from "next/navigation";
import { Card, Table, Button, Input, Space, Tag, Tooltip, Popconfirm, Typography, Image, Select } from "antd";
import { useMessage } from "@/hooks/useMessage";
import type { TablePaginationConfig } from "antd";
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, DownloadOutlined } from "@ant-design/icons";
import { adminAPI, adminUserAPI } from "@/lib/api";
import type { Product, ProductCategory, AdminUser } from "@/lib/api";
import AdminLayout from "@/components/AdminLayout";
import UserAvatar from "@/components/common/UserAvatar";

const { Text } = Typography;
const { Search } = Input;
const { Option } = Select;

export default function ProductsManagement() {
  const message = useMessage();
  const [products, setProducts] = useState<Product[]>([]);
  const [categories, setCategories] = useState<ProductCategory[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
    totalPages: 0,
  });
  const [searchKeyword, setSearchKeyword] = useState("");
  const [selectedCategory, setSelectedCategory] = useState<number | null>(null);
  const [selectedStatus, setSelectedStatus] = useState<boolean | null>(null);
  const [selectedUser, setSelectedUser] = useState<number | null>(null);
  const [users, setUsers] = useState<AdminUser[]>([]);
  const [exportLoading, setExportLoading] = useState(false);
  const router = useRouter();

  // 获取产品列表
  const fetchProducts = useCallback(async (page: number, pageSize: number, keyword?: string, categoryId?: number, status?: boolean, userId?: number) => {
    setLoading(true);
    try {
      const params = {
        page,
        pageSize,
        keyword,
        categoryId,
        status,
        userId,
      };
      const response = await adminAPI.getProducts(params);
      if (response.success) {
        setProducts(response.data.products);
        setPagination({
          current: response.data.page,
          pageSize: response.data.pageSize,
          total: response.data.total,
          totalPages: response.data.totalPages,
        });
      }
    } catch (error) {
      console.error("获取产品列表失败:", error);
      message.error("获取产品列表失败");
    } finally {
      setLoading(false);
    }
  }, []);

  // 获取分类列表
  const fetchCategories = useCallback(async () => {
    try {
      const response = await adminAPI.getProductCategories();
      if (response.success) {
        setCategories(response.data);
      }
    } catch (error) {
      console.error("获取产品分类失败:", error);
    }
  }, []);

  // 获取用户列表
  const fetchUsers = useCallback(async () => {
    try {
      const response = await adminUserAPI.getUsers();
      if (response.success) {
        setUsers(response.data);
      }
    } catch (error) {
      console.error("获取用户列表失败:", error);
    }
  }, []);

  // 删除产品
  const handleDeleteProduct = async (id: number) => {
    try {
      const response = await adminAPI.deleteProduct(id);
      if (response.success) {
        message.success("删除成功");
        fetchProducts(pagination.current, pagination.pageSize, searchKeyword, selectedCategory || undefined, selectedStatus || undefined, selectedUser || undefined);
      }
    } catch (error) {
      console.error("删除产品失败:", error);
      message.error("删除失败");
    }
  };

  // 处理预览 - 跳转到前台产品详情页
  const handlePreview = (record: Product) => {
    window.open(`/products/${record.slug}`, "_blank");
  };

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchKeyword(value);
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  // 处理分类筛选
  const handleCategoryChange = (value: number | null) => {
    setSelectedCategory(value);
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  // 处理状态筛选
  const handleStatusChange = (value: boolean | null) => {
    setSelectedStatus(value);
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  // 处理用户筛选
  const handleUserChange = (value: number | null) => {
    setSelectedUser(value);
    setPagination(prev => ({ ...prev, current: 1 }));
    // 立即触发数据获取
    fetchProducts(
      1,
      pagination.pageSize,
      searchKeyword || undefined,
      selectedCategory || undefined,
      selectedStatus || undefined,
      value || undefined
    );
  };

  // 处理表格变化
  const handleTableChange = (newPagination: TablePaginationConfig) => {
    fetchProducts(newPagination.current!, newPagination.pageSize!, searchKeyword || undefined, selectedCategory || undefined, selectedStatus || undefined, selectedUser || undefined);
  };

  // 处理新建产品
  const handleAddProduct = () => {
    router.push("/admin/products/edit");
  };

  // 处理编辑产品
  const handleEditProduct = (record: Product) => {
    router.push(`/admin/products/edit?id=${record.id}`);
  };

  // 处理导出
  const handleExport = async () => {
    setExportLoading(true);
    try {
      const blob = await adminAPI.exportProducts({
        keyword: searchKeyword || undefined,
        categoryId: selectedCategory || undefined,
        status: selectedStatus || undefined,
        userId: selectedUser || undefined,
      });
      
      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      
      // 生成文件名
      const now = new Date();
      const dateStr = now.toISOString().split('T')[0];
      link.download = `产品列表_${dateStr}.xlsx`;
      
      // 触发下载
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    } catch (error) {
      console.error('导出失败:', error);
      message.error('导出失败');
    } finally {
      setExportLoading(false);
    }
  };

  // 初始化数据
  useEffect(() => {
    fetchCategories();
    fetchUsers();
  }, [fetchCategories, fetchUsers]);

  useEffect(() => {
    fetchProducts(pagination.current, pagination.pageSize, searchKeyword || undefined, selectedCategory || undefined, selectedStatus || undefined, selectedUser || undefined);
  }, [pagination.current, pagination.pageSize, searchKeyword, selectedCategory, selectedStatus, selectedUser, fetchProducts]);

  // 表格列定义
  const columns = [
    {
      title: "产品Logo",
      dataIndex: "coverImage",
      key: "coverImage",
      width: 100,
      render: (url: string) => (url ? <Image src={url} width={80} height={60} style={{ objectFit: "cover" }} /> : "无"),
    },
    {
      title: "产品名称",
      dataIndex: "title",
      key: "title",
      render: (text: string) => <Text strong>{text}</Text>,
      ellipsis: true,
    },
    {
      title: "分类",
      dataIndex: "category",
      key: "category",
      width: 120,
      render: (category: { name: string } | undefined) => <Tag color='blue'>{category?.name || "-"}</Tag>,
    },
    {
      title: "开发者",
      dataIndex: "developerNickname",
      key: "developerNickname",
      width: 120,
      render: (developerNickname: string, record: Product) => (
        <div className='flex items-center space-x-2'>
          <UserAvatar src={record.developerAvatar} alt={developerNickname || record.author} size={24} showBorder={false} />
          <span>{developerNickname || record.author}</span>
        </div>
      ),
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      width: 80,
      render: (status: boolean) => <Tag color={status ? "green" : "red"}>{status ? "已发布" : "草稿"}</Tag>,
    },
    {
      title: "置顶",
      dataIndex: "isTop",
      key: "isTop",
      width: 60,
      render: (isTop: boolean) => <Tag color={isTop ? "orange" : "default"}>{isTop ? "置顶" : "-"}</Tag>,
    },
    {
      title: "推荐",
      dataIndex: "isRecommend",
      key: "isRecommend",
      width: 60,
      render: (isRecommend: boolean) => <Tag color={isRecommend ? "purple" : "default"}>{isRecommend ? "推荐" : "-"}</Tag>,
    },
    {
      title: "浏览量",
      dataIndex: "views",
      key: "views",
      width: 80,
      render: (views: number) => (
        <span>
          <EyeOutlined style={{ marginRight: 4 }} />
          {views?.toLocaleString?.() ?? 0}
        </span>
      ),
    },
    {
      title: "更新人",
      dataIndex: "author",
      key: "author",
      width: 100,
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
      key: "createdAt",
      width: 150,
      render: (date: string) => new Date(date).toLocaleDateString(),
    },
    {
      title: "操作",
      key: "action",
      fixed: "right" as const,
      width: 150,
      render: (_: unknown, record: Product) => (
        <Space size='small'>
          <Tooltip title='预览'>
            <Button type='text' icon={<EyeOutlined />} onClick={() => handlePreview(record)} />
          </Tooltip>
          <Tooltip title='编辑'>
            <Button type='text' icon={<EditOutlined />} onClick={() => handleEditProduct(record)} />
          </Tooltip>
          <Popconfirm title='确定要删除这个产品吗？' onConfirm={() => handleDeleteProduct(record.id)} okText='确定' cancelText='取消'>
            <Tooltip title='删除'>
              <Button type='text' danger icon={<DeleteOutlined />} />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <AdminLayout>
      <Card
        title='产品管理'
        extra={
          <Space>
            <Button
              icon={<DownloadOutlined />}
              onClick={handleExport}
              loading={exportLoading}
            >
              导出Excel
            </Button>
            <Button type='primary' icon={<PlusOutlined />} onClick={handleAddProduct}>
              新建产品
            </Button>
          </Space>
        }
      >
        <div style={{ marginBottom: 16 }}>
          <Space>
            <Search placeholder='输入关键词搜索' onSearch={handleSearch} enterButton style={{ width: 300 }} />
            <Select placeholder='选择分类' allowClear style={{ width: 150 }} onChange={handleCategoryChange} value={selectedCategory}>
              {categories.map(category => (
                <Option key={category.id} value={category.id}>
                  {category.name}
                </Option>
              ))}
            </Select>
            <Select placeholder='选择状态' allowClear style={{ width: 120 }} onChange={handleStatusChange} value={selectedStatus}>
              <Option value={true}>已发布</Option>
              <Option value={false}>草稿</Option>
            </Select>
            <Select placeholder='选择创作者' allowClear showSearch filterOption={(input, option) => String(option?.children || '').toLowerCase().includes(input.toLowerCase())} style={{ width: 150 }} onChange={handleUserChange} value={selectedUser}>
              {users.map(user => (
                <Option key={user.id} value={user.id}>
                  {user.username}
                </Option>
              ))}
            </Select>
          </Space>
        </div>
        <Table 
          columns={columns} 
          dataSource={products} 
          rowKey='id' 
          loading={loading} 
          pagination={{ 
            ...pagination, 
            total: pagination.total,
            showTotal: (total, range) => `共 ${total} 条记录，第 ${range[0]}-${range[1]} 条`,
            showSizeChanger: true,
            showQuickJumper: true,
            pageSizeOptions: ['10', '20', '50', '100'],
            showLessItems: true,
          }} 
          onChange={handleTableChange} 
          scroll={{ x: 1300 }} 
        />
      </Card>
    </AdminLayout>
  );
}
